<template>
  <div class="HomeLeft">
    <div class="title">
            <span>
                无人机影像图形转换
            </span>
      <img src="@/assets/images/title-icon.png" alt="" srcset="">
    </div>
    <div class="butList">
      <el-upload class="upload-demo"
                 action="string"
                 :http-request="UploadTIF"
                 :on-error="onError"
                 :on-success="handleAvatarSuccess"
                 :before-upload="beforeAvatarUpload"
                 :show-file-list="false"
                 :file-list="fileList">
        <div class="butItem">
          <img src="@/assets/images/Upload.png" alt="" srcset="">
          <span>TIF上传</span>
        </div>
      </el-upload>
      <div class="butItem" style="width: 100px;" @click="handleAdd">
        <i class="el-icon-plus"></i>
        <span>新增控制点</span>
      </div>
      <div class="butItem" @click="doCalibration">
        <img src="@/assets/images/convert.png" alt="" srcset="">
        <span>影像转换</span>
      </div>
      <div class="butItem" @click="doAutoOffset">
        <img src="@/assets/images/convert.png" alt="" srcset="">
        <span>自动转换</span>
      </div>
      <div class="butItem" @click="doPreview">
        <img src="@/assets/images/convert.png" alt="" srcset="">
        <span>转换预览</span>
      </div>
      <div class="butItem" @click="doExport">
        <img src="@/assets/images/download.png" alt="" srcset="">
        <span>影像下载</span>
      </div>
    </div>
    <div class="table">
      <el-table :data="tableData" stripe height="100%" border style="width: 100%"
                :header-cell-style="{ background: '#f1f1f1', color: '#000' }">
        <el-table-column align="center" label="序号" width="50">
          <template slot-scope="scope">
            <span class="SerialNumber">{{ scope.$index + 1 }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="SourcePointX" align="center" label="源点（像素坐标）">
          <template slot-scope="scope">
            <div class="SourcePoint">
                            <span @click="SourcePointhandleShow(scope.$index, 'SourcePointShow', 'targetShow')">
                              <template v-if="!scope.row.SourcePointX || !scope.row.SourcePointY">
                                请选择控制点
                              </template>
                              <template v-else>
                                ({{ scope.row.SourcePointX }} , {{ scope.row.SourcePointY }})
                              </template>
                            </span>
              <i class="el-icon-edit" v-if="scope.row.SourcePointShow"></i>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="targetX" align="center" label="靶点（经纬坐标）">
          <template slot-scope="scope">
            <div class="SourcePoint">
                            <span @click="SourcePointhandleShow(scope.$index, 'targetShow', 'SourcePointShow')">
                              <template v-if="!scope.row.targetX || !scope.row.targetY">
                                请选择控制点
                              </template>
                              <template v-else>
                                ({{ scope.row.targetX }} , {{ scope.row.targetY }})
                              </template>
                            </span>
              <i class="el-icon-edit" v-if="scope.row.targetShow"></i>
            </div>
          </template>
        </el-table-column>
        <el-table-column align="center" fixed="right" label="操作" width="100">
          <template slot-scope="scope">
            <el-button type="danger" @click="handleDelete(scope.$index)" icon="el-icon-delete" size="mini"
                       circle></el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
  </div>
</template>
<script>

import {convertToUTM49N} from "@/util/toUTM";
import {calibration, UploadTIF,autoOffset} from "@/api/geo";

export default {
  components: {},
  data() {
    return {
      fileList: [],
      tableData: [],
      spanArr: [],
      number: null,
      serialNumber: 1,
      sourceId: null,
      sourceGeoTransform: null,
      sourceImgUrl: null,
      sourceWidth: null,
      sourceHeight: null,
      targetId: null,
      targetGeoTransform: null,
      targetWidth: null,
      targetHeight: null,
      gisName: null,
      convertTask:null,
      lon:null,
      lat:null,
      espgCode:null
    }
  },
  created() {
    // this.getSpanArr(this.tableData);
  },
  mounted() {
    this.initEpgis((epgis,sgKey,sgSecret) =>{
      this.gisName=epgis;
      this.gisName.tokenTask.login(
          sgKey,
          sgSecret
      ).then(() =>{
        this.convertTask = new this.gisName.ConvertTask();
      })
    })
    // setTimeout(() => {
    //   this.sourceId = "f688495f-8599-4130-841b-4227016d6265";
    //   this.sourceGeoTransform = [647704.3856713088, 0.0338, 0.0, 3879116.430349915, 0.0, -0.0338];
    //   this.sourceHeight = 31576;
    //   this.sourceWidth = 37539;
    //   this.$emit('sourceFileUpload', {
    //     'sourceId' : this.sourceId,
    //     'sourceGeoTransform' : this.sourceGeoTransform,
    //     'sourceImgUrl' : this.sourceImgUrl,
    //     'row': this.sourceHeight,
    //     'col': this.sourceWidth,
    //   })
    // }, 2000);
  },
  methods: {
    doCalibration() {
      if(!this.sourceId) {
        this.$message(    {
          message: "请选择先上传文件！",
          type: 'warning'
        });
        return;
      }
      let srcPoint = [];
      let tarPoint = [];
      for (let i = 0; i < this.tableData.length; i++) {
        let row = this.tableData[i];
        if(!row.SourcePointX || !row.SourcePointY || !row.targetX || !row.targetY) {
          this.$message(    {
            message: "存在未配准的控制点！",
            type: 'warning'
          });
          return;
        }

        srcPoint.push([row.SourcePointX, row.SourcePointY]);
        tarPoint.push(convertToUTM49N(row.targetX, row.targetY,this.espgCode));
      }

      if(srcPoint.length < 3) {
        this.$message(    {
          message: "请选择至少三组控制点！",
          type: 'warning'
        });
        // return;
      }

      const formData = new FormData();
      formData.append("source_points", JSON.stringify(srcPoint));
      formData.append("target_points", JSON.stringify(tarPoint));
      formData.append("uuid", this.sourceId);
      formData.append("espgCode",this.espgCode)

      // 调用配准接口
      this.$emit('loadingCalibration');
      calibration(formData).then(res => {
        if(res['status_code'] === '200') {
          this.targetId = res['affineTif_uuid'];
          this.targetGeoTransform = res['affine_geojson'];
          this.targetWidth = res['output_width'];
          this.targetHeight = res['output_height'];
          this.$message({
            message: "地理配准成功！",
            type: 'success'
          });
        }
      }).finally(() => {
        this.$emit('loadedCalibration');
      })
    },
    doPreview() {
      if(!this.targetId || !this.targetGeoTransform) {
        this.$message.warning("请先进行地理配准!");
        return;
      }
      this.$emit('showPreview', {
        'targetId': this.targetId,
        'targetGeoTransform': this.targetGeoTransform,
        'targetWidth' : this.targetWidth,
        'targetHeight': this.targetHeight,
        'espgCode': this.espgCode
      });
    },
    initEpgis(callback){
      fetch('/api/getSJConfig') // 假设后端接口是 /api/config
          .then(response => response.json()) // 将响应数据解析为 JSON
          .then(data => {
            let linkSGScript =document.createElement("link");
            let secSGScript = document.createElement("script");
            let href = data.sgApi + '/api/epgis-1.5.0.css';
            let src = data.sgApi + '/api/epgis-js-1.5.0.min.js';
            linkSGScript.setAttribute("rel","stylesheet")
            linkSGScript.setAttribute("href",href)
            document.head.insertBefore(linkSGScript,document.head.lastChild);
            secSGScript.setAttribute("src",src)
            document.head.insertBefore(secSGScript,document.head.lastChild);
            secSGScript.onload=secSGScript.onreadystatechange=function() {
              if(!this.readyState ||this.readyState==="loaded" || this.readyState==="complete"){
                secSGScript.onload=secSGScript.onreadystatechange=null;
                if(callback && typeof callback=="function"){
                  if(typeof epgis !='undefined'){
                    callback(epgis,data.sgKey,data.sgSecret)
                  }
                }
              }
            }
          })
    },
    doAutoOffset() {
      if(null==this.sourceId){
        this.$message({
          message: "请先上传文件！",
          type: 'warning'
        });
        return;
      }
      this.$emit('loadingCalibration');
      const formData = new FormData();
      formData.append("uuid", this.sourceId);
      formData.append("espgCode",this.espgCode)
      var coords = [this.lon,this.lat];
      console.log("转换前坐标",coords)
      this.convertTask.convertCoord([coords], {
        from: 1
      }).then((result) => {
        console.log("转换后坐标",result)
        formData.append("lonlat",result);
        autoOffset(formData).then(res => {
          if(res['status_code'] === '200') {
            console.log(res)
            this.targetId = res['affineTif_uuid'];
            this.targetGeoTransform = res['affine_geojson'];
            this.targetWidth = res['output_width'];
            this.targetHeight = res['output_height'];
            this.$message({
              message: "自动偏移成功！",
              type: 'success'
            });
          }
        }).finally(() => {
          this.$emit('loadedCalibration');
        })
      })
    },
    doExport() {
      // if(!this.targetId) {
      //   this.$message({
      //     message: "未获取到对应配准图像！",
      //     type: 'warning'
      //   });
      //   return;
      // }
      // window.location.href = `/api/download/${this.targetId}`;

      this.$emit('doExport', this.targetId,this.espgCode);
    },
    UploadTIF(param) {
      const formData = new FormData();
      let file = param.file;
      formData.append('files', file); // 将文件对象添加到 FormData 中
      this.$emit('resetTIF');
      this.$emit('uploadTIF', {
        status: 'uploading',
        val: 0
      });
      UploadTIF(formData, (process) => {
        this.$emit('uploadTIF', {
          status: 'uploading',
          val: process
        });
        if(process >= 100) {
          this.$emit('uploadTIF', {
            status: 'analysis',
          });
        }
      }).then(res => {
        let {status_code, results} = res;
        if(status_code === 200) {
          console.log(res)
          let result = results[0];
          this.updateSource(result);
          param.onSuccess()
        }
        else
          param.onError()
      }).catch(err => {
        param.onError()
      });
    },
    updateSource(result) {
      this.sourceId = result['tif_rawdataId'];
      this.sourceGeoTransform = JSON.parse(result['geojson']);
      this.sourceImgUrl = result['image_url'];
      this.sourceWidth = result['width'];
      this.sourceHeight = result['height'];
      this.espgCode=result['espgCode'];
      this.lon=result['lon'];
      this.lat=result['lat'];
    },
    handleAvatarSuccess() {
      this.$emit('sourceFileUpload', {
        'sourceId' : this.sourceId,
        'sourceGeoTransform' : this.sourceGeoTransform,
        'sourceImgUrl' : this.sourceImgUrl,
        'row': this.sourceHeight,
        'col': this.sourceWidth,
      })
    },
    resetTIF() {
      this.serialNumber = 1;
      this.sourceId = null;
      this.sourceGeoTransform = null;
      this.sourceImgUrl = null;
      this.sourceWidth = null;
      this.sourceHeight= null;
      this.targetId = null;
      this.targetGeoTransform = null;
      this.targetWidth = null;
      this.targetHeight = null;
      this.espgCode=null;
      for (let i = 0; i < this.tableData.length; i++) {
        this.$emit('deleteCP', this.tableData[i].serialNumber);
      }
      this.tableData = [];
    },
    beforeAvatarUpload() {
      // console.log(file);
    },
    onError(e) {
      console.log(e);
    },
    handleAdd() {
      this.tableData.push({
        SourcePointShow: false,
        targetShow: false,
        serialNumber: this.serialNumber++
      });
    },
    handleDelete(index, force= false) {
      let promise = new Promise((resolve, reject) => {
        if(!force) {
          this.$confirm('此操作将删除该控制点， 是否继续?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
            resolve();
          }).catch(() => {
            this.$message({
              type: 'info',
              message: '已取消删除'
            });
            reject();
          });
        }
        else resolve();
      })

      promise.then(() => {
        let serialNumber = this.tableData[index].serialNumber;
        this.$emit('deleteCP', serialNumber);

        this.tableData.splice(index, 1);
        this.$message({
          type: 'success',
          message: '删除成功!'
        });
      });
    },
    SourcePointhandleShow(e, show1, show2) {
      this.number = e;
      for (let index = 0; index < this.tableData.length; index++) {
        if (index == this.number) {
          this.tableData[index][show1] = true;
        } else {
          this.tableData[index][show1] = false;
        }
        this.tableData[index][show2] = false;
      }

      if (show1 === 'SourcePointShow') {
        this.$emit('actModeChange', 'sourceCP', this.tableData[e].serialNumber, (result) => {
          this.tableData[e][show1] = false;
          this.tableData[e]['SourcePointX'] = Number.parseInt(result.x);
          this.tableData[e]['SourcePointY'] = Number.parseInt(result.y);
        });
      } else {
        this.$emit('actModeChange', 'targetCP', this.tableData[e].serialNumber, (result) => {
          this.tableData[e][show1] = false;
          this.tableData[e]['targetX'] = result.lng;
          this.tableData[e]['targetY'] = result.lat;
        });
      }

    },
    // tableRowClassName({ row, rowIndex }) {
    //     if (rowIndex === 0) {
    //         return 'warning-row';
    //     }
    //     return '';
    // },
    // /** 合并单元格数据 */
    // getSpanArr(data) {
    //     for (var i = 0; i < data.length; i++) {
    //         if (i === 0) {
    //             this.spanArr.push(1);
    //             this.pos = 0
    //         } else {
    //             // 判断当前元素与上一个元素是否相同
    //             if (data[i].id === data[i - 1].id) {
    //                 this.spanArr[this.pos] += 1;
    //                 this.spanArr.push(0);
    //             } else {
    //                 this.spanArr.push(1);
    //                 this.pos = i;
    //             }
    //         }
    //     }
    // },
    // /** 合并单元格 */
    // objectSpanMethod({ row, column, rowIndex, columnIndex }) {
    //     if (columnIndex === 0) {
    //         const _row = this.spanArr[rowIndex];
    //         const _col = _row > 0 ? 1 : 0;
    //         return { // [0,0] 表示这一行不显示， [2,1]表示行的合并数
    //             rowspan: _row,
    //             colspan: _col
    //         }
    //     }
    // },

  },
};
</script>
<style lang="scss" scoped>
.HomeLeft {
  width: 100%;
  height: 100%;
  padding: 5px 10px;
  box-sizing: border-box;
  border-radius: 5px;
  background: url(@/assets/images/back-left.png) no-repeat top center / 105% 100px;
  background-color: #fff;
  box-shadow: 0px 0px 10px #007975;


  .title {
    width: 100%;
    height: 30px;
    display: flex;
    align-items: center;
    font-size: 22px;
    font-weight: bold;
    color: #fff;
    position: relative;

    span {
      position: absolute;
      z-index: 10;
      text-shadow: 0px 0px 5px #585858;
    }

    img {
      position: absolute;
      bottom: 1px;
      z-index: 0;
    }
  }

  .butList {
    width: 100%;
    height: 40px;
    display: flex;
    display: flex;
    align-items: center;

    .butItem {
      width: 100px;
      height: 30px;
      display: flex;
      justify-content: center;
      align-items: center;
      background: linear-gradient(to bottom, #6ed2cd, #30bbac);
      border-radius: 5px;
      color: #fff;
      border: 1px solid #3aa39d;
      cursor: pointer;
      margin-right: 10px;

      img {
        width: 15px;
        margin-right: 5px;
      }

      span {
        font-size: 13px;
      }

      &:hover {
        background: #69bfba;
      }

      &:active {
        background: linear-gradient(to bottom, #6ed2cd, #30bbac);
      }
    }
  }

  .table {
    width: 100%;
    height: calc(100% - 70px);
  }
}

.SourcePoint {
  display: flex;
  align-items: center;
  justify-content: center;
  position: relative;

  span {
    cursor: pointer;

    &:hover {
      color: #d6882e;
      text-decoration: underline;
    }
  }

}

.el-icon-edit {
  cursor: pointer;
  font-size: 15px;
  font-weight: bold;
  color: #d6882e;
  position: absolute;
  right: 10px;
  top: 50%;
  transform: translateY(-50%);
}

.SerialNumber {
  font-weight: bold;
  font-size: 16px;
  color: #cbcbcb;
}

::v-deep .el-table--striped .el-table__body tr.el-table__row--striped td.el-table__cell {
  background: #f4fbfc;
}

::v-deep .el-table .warning-row {
  background: rgb(254, 245, 231) !important;
}

::v-deep .el-table .el-table__cell {
  padding: 3px 0;
}
</style>
